package com.test.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Component
@Slf4j
public class CommandUtils {

    public String exec(String command) {

//        String[] commands = { "cmd", "/c", command };
//        String encodeType = "GBK";
        String[] commands = { "/bin/sh", "-c", command };
        String encodeType = "UTF-8";

        try {
            Process process = Runtime.getRuntime().exec(commands);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), encodeType));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {

                if (line.contains("/bin/sh -c")) {
                    log.info("这行数据不要：{}", line);
                } else {
                    buffer.append(line).append("\n");
                }
            }
            reader.close();

            log.info("命令`{}`执行结果：{}", command, buffer.toString().trim());

            return buffer.toString().trim();
        } catch (IOException e) {
            log.error("执行命令{}失败，信息：{}", command, e);
            return "";
        }
    }

    public static void main(String[] args) {

        CommandUtils agentUtils = new CommandUtils();

        System.out.println(agentUtils.exec("ipconfig"));
    }
}
